package com.zzwtel.autocode.beetl;

import java.util.HashMap;
import java.util.Map;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;
import com.zzwtel.autocode.template.constants.TemplatePath;
import com.zzwtel.autocode.template.model.EntityModel;
import com.zzwtel.autocode.util.FileUtil;
import com.zzwtel.autocode.util.HumpUtil;
import com.zzwtel.autocode.util.PathUtil;
import com.zzwtel.autocode.util.StrKit;

/**
 * @author  草原狼
 *
 * 2017年8月3日
 */

public class SpringRestControllerTestTemplate {
	/**
	 * 生成代码
	 * @param tm
	 */
	public void generate(EntityModel tm) {		
		try{
			//准备工作#######################
			String root = PathUtil.getTemplateRoot();
			FileResourceLoader resourceLoader = new FileResourceLoader(root,"utf-8");
			Configuration cfg = Configuration.defaultConfiguration();
			GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
				
			Template t = gt.getTemplate(TemplatePath.SPRING_REST_CONTROLLER_TEST_JAVA_FILE_TEMPLATE);
			
			
			String ctrlPkg = "com.zzwtec.information.controller";
			String daoPkg = "com.zzwtec.information.dao";
			String modelPkg = "com.zzwtec.information.model";
			String dtoPkg = "com.zzwtec.interfaces.information.dto";
			String servicePkg = "com.zzwtec.interfaces.information.services";
			
			//绑定数据#######################
			t.binding("ctrlPkg", ctrlPkg);
			t.binding("daoPkg", daoPkg);
			t.binding("modelPkg", modelPkg);
			
			t.binding("dtoPkg", dtoPkg);	
			
			t.binding("servicePkg", servicePkg);	
			
			String model = tm.getTable().getModel();			
			//首字母小写，驼峰命名
			t.binding("entityModel", model);
			//首字母大写，驼峰命名
			t.binding("EntityModel", StrKit.firstCharToUpperCase(model));
			//全部大写，下划线分割
			String _model = HumpUtil.underscoreName(model);
			t.binding("ENTITY_MODEL", _model);
			//全部小写，下划线分割			
			t.binding("entity_model", HumpUtil.toLowerCase(_model));	
			//绑定表名
			t.binding("tableName", tm.getTable().getName());
			//开始绑定sql语句
			t.binding("entityModel", model);			
			
			
			//构造路径#######################			
			String data = t.render();			
			String out = PathUtil.getOutRoot();		
			Map<String,String> map = new HashMap<String,String>();
			//先写死路径吧
			map.put("pkg", pkg2Path(ctrlPkg));
			map.put("EntityModel", StrKit.firstCharToUpperCase(model)+"ControllerTest");
			String fileName = StringTemplate.getFileName(TemplatePath.TEST_JAVA_FILE_OUTPUT,map);		
			FileUtil.write(out+fileName, data);
			
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
	private String pkg2Path(String pkg){
		return pkg.replace(".", "/");
	}
	
}
